package biz

import (
	"context"
	itempb "gitee.com/shuokeyun/apis/item-service/api/v1"
	merchantpb "gitee.com/shuokeyun/apis/merchant-service/api/v1"
	orderpb "gitee.com/shuokeyun/apis/order-service/api/v1"
	"gitee.com/shuokeyun/kratos/errors"
	"gitee.com/shuokeyun/med-bff/internal/domain"
	"google.golang.org/genproto/protobuf/field_mask"
)

var _ domain.OrderUsecase = (*orderUsecase)(nil)

type orderUsecase struct {
	orderClient    orderpb.OrderClient
	merchantClient merchantpb.MerchantClient
	itemClient     itempb.ItemClient
}

func NewOrderUsecase(orderClient orderpb.OrderClient, merchantClient merchantpb.MerchantClient, itemClient itempb.ItemClient) domain.OrderUsecase {
	return &orderUsecase{
		orderClient:    orderClient,
		merchantClient: merchantClient,
		itemClient:     itemClient,
	}
}

func (o *orderUsecase) CreateOrder(ctx context.Context, do *domain.CreateOrder) (int64, error) {
	merchant, err := o.merchantClient.GetMerchant(ctx, &merchantpb.GetMerchantRequest{
		Id: do.MerchantId,
	})
	if err != nil {
		return 0, err
	}
	var itemCodes []string
	for _, barcode := range do.Barcodes {
		itemCodes = append(itemCodes, barcode.ItemCodes...)
	}
	itemCodes = append(itemCodes, do.OriginalItemCodes...)
	items, err := o.itemClient.GetItems(ctx, &itempb.GetItemsRequest{
		Code:      itemCodes,
		Brand:     do.Brand,
		PriceArea: merchant.PriceArea,
		FieldMask: &field_mask.FieldMask{
			Paths: []string{"code", "brand", "price_area", "name", "market_price", "cost_price", "can_separate",
				"checked_with_item", "sex_limit", "child_item", "reject_item"},
		},
	})
	if err != nil {
		return 0, err
	}
	if len(items.Data) != len(itemCodes) {
		return 0, errors.ErrorArgument("项目不存在")
	}
	request := doConvCreateOrderRequest(do, merchant, items.Data)
	re, err := o.orderClient.CreateOrder(ctx, request)
	if err != nil {
		return 0, err
	}
	return re.Id, nil
}
